package com.huafeng.commonutil;

import com.huafeng.model.entity.SysMenu;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 花风
 * @date 2023/8/17 11:54
 * @Description 菜单生成类
 */
public class MenuHelper {

    private MenuHelper(){
    }

    public static List<SysMenu> buildTree(List<SysMenu> roots,List<SysMenu> sysMenuList) {
        List<SysMenu> result = new ArrayList<>();

        // 遍历根结点
        roots.forEach(root -> {
            root.setChildren(new ArrayList<>());
            // 获取根结点的子节点
            List<SysMenu> children = getChildren(root, sysMenuList);
            // 遍历子节点
            children.forEach(sysMenu -> {
                sysMenu.setChildren(new ArrayList<>());
                sysMenu.getChildren().addAll(getChildren(sysMenu,sysMenuList));
            });

            root.getChildren().addAll(children);
            result.add(root);
        });
        return result;
    }

    public static List<SysMenu> getChildren(SysMenu sysMenu, List<SysMenu> sysMenuList){
        Long menuId = sysMenu.getId();
        // 从SysMenuList中筛选出parentId为menuId
        return sysMenuList.stream().filter(menu -> Objects.equals(menuId, menu.getParentId())).collect(Collectors.toList());
    }
}
